import hashlib
import hmac
import traceback
import uuid

from models import user
from models.user import get_sms_code
from views import BaseHandler, SMSHandler
from configs import errorCode, errorMsg, config, const
from utils import util

from alipay import AliPay
from alipay.utils import AliPayConfig

from configs import ali

alipay = AliPay(
    appid=ali.appid,
    app_notify_url=None,  # 默认回调url
    app_private_key_string=ali.app_private_key,
    # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
    alipay_public_key_string=ali.ali_public_key,
    sign_type="RSA2",
    debug=False,
    config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
)


class GenPayLinkHandler(BaseHandler):
    @BaseHandler.auth
    async def get(self):
        """
        ---
        tags:
          - Pay
        summary: 短信注册，提交用户信息
        description: 接受上一步的短信验证码，用户名，密码，注册，注册成功返回cookie设置保持登录
        parameters:
          - name: order_id
            in: query
            description: 订单号
            required: true
            schema:
              type: string
          - name: user_token
            in: header
            description:
            required: true
            schema:
              type: string

        responses:
          '200':
            description: successful operation
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/OkModel'
          '400':
            description: error operation
            content:
              application/json:
                schema:
                  $ref: '#/components/schemas/ErrorModel'
        """
        order_id = 20201026112233
        total_amount = 0.01
        subject = 'mall_demo%s' % order_id
        order_string = alipay.api_alipay_trade_wap_pay(
            out_trade_no=order_id,
            total_amount=total_amount,
            subject=subject,
            return_url="https://example.com",
            notify_url="https://example.com/notify",  # 可选, 不填则使用默认notify url
            quit_url="https://www.baidu.com"
        )
        # 响应登录支付宝连接
        # 真实环境电脑网站支付网关：https://openapi.alipay.com/gateway.do? + order_string
        # 沙箱环境电脑网站支付网关：https://openapi.alipaydev.com/gateway.do? + order_string
        alipay_url = ali.alipay_gateway + "?" + order_string
        return self.write_json(alipay_url)

    async def post(self):
        data = util.json_decode(self.request.body)
        # sign 不能参与签名验证
        signature = self.get_body_argument('sign')

        print(signature)

        # verify
        success = alipay.verify(data, signature)
        if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
            print("trade succeed")
        # 存入数据库

        return self.write("success")


class PayInfoHandler(BaseHandler):
    @BaseHandler.auth
    async def get(self):
        # 获取用户支付信息，若数据库没有，则发请求到支付宝
        pass
